from django.shortcuts import render,HttpResponse
from django.shortcuts import redirect
from django.views import View
import json
from .models import Book
# Create your views here.

def books(request):
    book_list = Book.objects.all()
    return render(request, 'base.html', {'book_list': book_list})

def add_book(request):
    if request.method == 'POST':
        title = request.POST.get('title', None)
        price = request.POST.get('price', None)
        pub_date = request.POST.get('pub_date', None)
        publish = request.POST.get('publish', None)

        Book.objects.create(title=title, price=price, pub_date=pub_date, publish=publish)
    return redirect('/')

def del_book(request):
    status = {'status': None}
    bid = request.POST.get('bid', None)
    res = Book.objects.filter(id=bid).delete()
    if res[0]:
        status['status'] = True
        return HttpResponse(json.dumps(status))
    else:
        status['status'] = False
        return HttpResponse(json.dumps(status))

# def edit_book(request):
#     if request.method == 'POST':
#         bid = request.POST.get('bid', None)
#         title = request.POST.get('title', None)
#         price = request.POST.get('price', None)
#         pub_date = request.POST.get('pub_date', None)
#         publish = request.POST.get('publish', None)
#
#         Book.objects.filter(id=bid).update(title=title,price=price,pub_date=pub_date,publish=publish)
#
#     return redirect('/')


class EditBook(View):
    def post(self, request):
        bid = request.POST.get('bid', None)
        title = request.POST.get('title', None)
        price = request.POST.get('price', None)
        pub_date = request.POST.get('pub_date', None)
        publish = request.POST.get('publish', None)

        Book.objects.filter(id=bid).update(title=title,price=price,pub_date=pub_date,publish=publish)

        return redirect('/')